<?php

namespace App\Http\Controllers\Api;

use App\Libs\WeChat\WxSmallClient;
use App\Models\like_count;
use App\Models\mcds_users;
use App\Models\member_bonus_record;
use App\Models\sign_record;
use App\Models\user;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redis;
use Ixudra\Curl\Facades\Curl;

class UserController extends Controller
{

    const LEVEL= ['环保新秀',// 正常
        "环保少侠",
        "环保大侠",
        "环保掌门",
        "环保宗师",
        "环保盟主",
    ];

    /**
     * regist 注册，以及获取token凭证接口
     */
    public function regist(Request $request)
    {
//        $code = $request->json('code');
//        $iv = $request->json('iv');
//        $cryptData = $request->json('cryptData');
//        //$activity = (int) $request->json('activity', 0); // 活动进入用户标记
//
//        if (empty($code) || empty($iv) || empty($cryptData)) {
//            fun_respon(0, '缺少参数');
//        }
//        $rs = WxSmallClient::getSessionKey($code);
//        $array_user = json_decode($rs);
//        if (!is_object($array_user)) {
//            fun_respon(0, '网络异常请重试');
//        }
//        if ( !property_exists($array_user, 'session_key')) {
//            fun_respon(0, '解码失败');
//        }
//
//
//        $userDatas = WxSmallClient::decryptData($array_user->session_key, $iv, $cryptData);
//        $userData = json_decode($userDatas, true);
//        if (is_array($userData) && !empty($userData)) {
//            // 去添加用户
//            $openid = $userData['openId'];
//            $uinfo = user::where('openid', $userData['openId'])->first();
//            if (!$uinfo) {
//                $add_data = [
//                    'openid' => $openid,
//                    'unionid' => $userData['unionId'],
//                ];
//                $res = user::insertGetId($add_data);
//                $uinfo = user::where('id', $res)->first();
//            }else{
//                if(!$uinfo['unionid']){
//                    $res = user::where('openid', $userData['openId'])->update(['unionid' => $userData['unionId']]);
//                    if(!$res) fun_respon(0, '更新数据错误');
//                }
//            }
//            $token = Crypt::encrypt(['openid'=>$openid]);
//            Redis::setex('token_'.$openid, 14400, $token);
//            fun_respon(1, ['token'=>$token,"info"=>$uinfo->toArray()]);
//        }
//        fun_respon(0, '数据错误');
        $code = $request->json('code');
        if (empty($code)) fun_respon(0, '缺少参数');

        $rs = WxSmallClient::getSessionKey($code);

        $array_user = json_decode($rs);
        if (!is_object($array_user)) {
            fun_respon(0, '网络异常请重试');
        }
        if ( !property_exists($array_user, 'session_key')) {
            fun_respon(0, '解码失败');
        }
        $openid = $array_user->openid;
        $user = user::where('openid', $openid)->first();
        if (!empty($user)) {
            $token = Crypt::encrypt(['openid'=>$user['openid']]);
            Redis::set('token_'.$openid, $token);
            //计算总积分
            $total = $this->getbonus(['openid'=>$openid,'type'=>1]);
            $level = get_level($total);
            $user['level'] = self::LEVEL[$level];
            fun_respon(1, ['token'=>$token, 'info'=>$user->toArray()]);
        }
        $add_data = [
            'openid' => $openid,
            'bonus' => 0
        ];
        if (property_exists($array_user, 'unionid')) {
            $add_data['unionid'] = $array_user->unionid;
        }
        $res = user::insertGetId($add_data);
        $token = Crypt::encrypt(['openid'=>$openid]);
        Redis::set('token_'.$openid, $token);
        $uinfo = user::where('id', $res)->first();
        //计算总积分
        $total = $this->getbonus(['openid'=>$openid,'type'=>1]);
        $level = get_level($total);
        $uinfo['level'] = self::LEVEL[$level];
        if ($res) fun_respon(1, ['token'=>$token,"info"=>$uinfo->toArray()]);
        fun_respon(0, '注册失败');

    }
    

    /**
     * 用户注册 获取token
     * @param Request $request
     */
    public function usersregist(Request $request)
    {
        $openid = $request->json('openid');
        if (empty($openid)) fun_respon(0, '缺少参数');
        $user = user::where('openid', $openid)->first();
        $token = Crypt::encrypt(['openid'=>$openid]);
        if (!empty($user)) {
            Redis::setex('token_'.$openid, 14400, $token);
            fun_respon(1, ['token'=>$token, 'info'=>$user->toArray()]);
        }

        $res = user::insert(['openid'=>$openid]);
        $token = Crypt::encrypt(['openid'=>$openid]);
        if ($res) {
            Redis::setex('token_'.$openid, 14400, $token);
            fun_respon(1, ['token'=>$token]);
        }
        fun_respon(0, '注册失败');
    }

    /**
     * 获取用户信息
     */
    public function userinfo(Request $request)
    {
        $openid = $request->openid;
        $userinfo = user::where('openid', $openid)->first();
        if (!$userinfo) fun_respon(0, '用户未注册');
        fun_respon(1, $userinfo->toArray());
    }


    private function getbonus($where){
        $total = member_bonus_record::where($where)->sum('change_bonus');
        return $total;
    }

    /**
     * 修改用户信息
     */
    public function edituser(Request $request)
    {
        $openid = $request->openid;
        $nickname = $request->json('nickName');
        $header_url = $request->json('avatarUrl');
        $constellation = $request->json('constellation');
        $age = $request->json('age');
        $phone = $request->json('phone');
        $sex = $request->json('gender');

        $params = [
            'nickName' => $nickname,
            'avatarUrl' => $header_url,
            'constellation' => $constellation,
            'age' => $age,
            'phone' => $phone,
            'gender' => $sex,
            'ut' => date('Y-m-d H:i:s'),
        ];
        $res = user::where('openid', $openid)->update($params);
        if ($res) fun_respon(1, '修改成功');
        fun_respon(1, '修改失败');
    }

    /**
     * 喜好统计
     */
    public function getlike(Request $request)
    {
        $openid = $request->openid;
        $taste = $request->json('taste');
        $whos = $request->json('whos');
        $proposal = $request->json('proposal');

        if (empty($taste) || empty($whos)) {
            fun_respon(0, '缺少参数');
        }

        $data = [
            'taste' => $taste,
            'whos' => $whos,
            'proposal' => $proposal,
            'openid' => $openid,
        ];
        $res = like_count::insert($data);
        if ($res) {
            fun_respon(1, '添加成功');
        }
        fun_respon(0, '添加失败');
    }


    public function bonusList(Request $request){
        $openid = $request->openid;
        $res = member_bonus_record::where(['openid'=>$openid])->orderBy('created_at','DESC')->get(['id','change_bonus','after_bonus','type','status','created_at']);
        if($res){
            foreach ($res as &$v){
                if($v['status']==1){
                    $v['status']='消费';
                }elseif($v['status']==2){
                    $v['status']='签到';
                }elseif($v['status']==3){
                    $v['status']='回收';
                }
            }
            fun_respon(1, $res);
        }
        fun_respon(0,'暂无数据！' );
    }


    /**
     * @param Request $request
     * 更新用户信息
     */
    public function updateUser(Request $request){
        $openid = $request->openid;
        $avatarUrl = $request->json('avatarUrl','');
        $city = $request->json('city','');
        $country = $request->json('country','');
        $province = $request->json('province','');
        $gender = $request->json('gender','');
        $nickName = $request->json('nickName','');
        user::where(['openid'=>$openid])->update(['avatarUrl'=>$avatarUrl,'city'=>$city,'country'=>$country,'gender'=>$gender,'nickName'=>$nickName,'province'=>$province]);
        fun_respon(1, '成功');
    }


    /**
     * @param Request $request
     * 添加签到
     */
    public function addSign(Request $request){
        $openid = $request->openid;
        $sign_info = sign_record::where(['openid'=>$openid])->orderBy('id','DESC')->first();
        //判断最后一条的签到记录 如果存在则判断是否为今天 ，不是则签到，如果不存在 直接添加新记录
        $date = date('Y-m-d');
        if($sign_info){
            if($date==date('Y-m-d',strtotime($sign_info['created_at']))){
                fun_respon(0, '今天已经签到过了！');
            }else{
                $data['openid'] = $openid;
                $data['continuous_days'] = $sign_info['continuous_days']+1;
                $data['sign_day'] = $sign_info['sign_day']+1;
                if($data['sign_day']>7) $data['sign_day']=1;
            }
        }else{
            $data['openid'] = $openid;
            $data['continuous_days'] = 1;
            $data['sign_day'] = 1;
        }
        $bonus = ($data['continuous_days']%7)==0?6:5;
        $res = sign_record::insert($data);
        if($res){
            //添加积分
            $member_info = get_member($openid);
            if($member_info){
                $before_bonus = $member_info['bonus'];
                $change_bonus = $bonus;
                $after_bonus = $before_bonus+$change_bonus;
                $status = 2;
                $type = 1;
                //调用微信的接口加积分
                $record_bonus = sprintf("签到,增加积分%s", $bonus);
                //$result = WxSmallClient::updateMember($member_info['code'],$record_bonus,$change_bonus);
                add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,2);

            }
            fun_respon(1, '签到成功！');
        }
        fun_respon(0, '签到失败！');
    }



    public function getUser(){
        $id = 25086311;
        $pageSize = 1;
        while (1){
                $url = "https://minapp.mcdonalds.com.cn/api/test/getusers";
                $dataRes = Curl::to($url)
                    ->withData(['pageSize'=>$pageSize,'id'=>$id])
                    ->post();
                $data = json_decode($dataRes,true);
                var_dump($data);
                var_dump($data['result']==1);
                if($data['result']==1){
                    $res = mcds_users::insert($data['data']);
                    var_dump($res);
                    $id += $pageSize;
                    //savelog('user_result', ''.$res.'id：'.$id);
                    var_dump($id);
                }
                echo  '2222';
        }

    }

}
